package com.sj.parksdk.fragment.certificate;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.ruffian.library.widget.RLinearLayout;
import com.ruffian.library.widget.RTextView;
import com.ruffian.library.widget.helper.RBaseHelper;
import com.ruffian.library.widget.helper.RTextViewHelper;
import com.sj.parksdk.R;
import com.sj.parksdk.R2;
import com.sj.parksdk.core.BaseFragment;
import com.sj.parksdk.core.http.subscriber.TipRequestSubscriber;
import com.sj.parksdk.fragment.carmanage.FragmentParkingPay;
import com.sj.parksdk.net.base.CommonResult;
import com.sj.parksdk.net.http.ApiHelper;
import com.sj.parksdk.net.http.MyNetApi;
import com.sj.parksdk.net.http.callback.TipRequestCallBack;
import com.sj.parksdk.net.request.MGetRequest;
import com.sj.parksdk.net.result.databean.Data_Car;
import com.sj.parksdk.net.result.databean.Data_CarLicense;
import com.sj.parksdk.setting.Dictionary;
import com.sj.parksdk.setting.Extras;
import com.sj.parksdk.utils.Utils;
import com.sj.parksdk.utils.XToastUtils;
import com.sj.parksdk.widget.sweetalert.SweetAlertDialog;
import com.xuexiang.xaop.annotation.Permission;
import com.xuexiang.xaop.annotation.SingleClick;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xhttp2.request.CustomRequest;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xrouter.annotation.AutoWired;
import com.xuexiang.xrouter.launcher.XRouter;
import com.xuexiang.xui.utils.DensityUtils;
import com.xuexiang.xui.utils.ResUtils;
import com.xuexiang.xui.widget.textview.supertextview.SuperTextView;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.net.JsonUtil;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.xuexiang.xaop.consts.PermissionConsts.STORAGE;

@Page(name = "车辆认证", params = {Extras.CAR_ID, Extras.CAR_COLOR, Extras.CAR_IS_CETIFICAT, Extras.CAR_NUMBER})
public class FragmentCarCertificate extends BaseFragment {
    @BindView(R2.id.tv_name)
    TextView tvName;
    @BindView(R2.id.rtv_car_color)
    RTextView rtvCarColor;
    RTextViewHelper rtvCarColorHelper;
    @BindView(R2.id.rll_car_color)
    RLinearLayout rllCarColor;
    RBaseHelper rllCarColorHelper;
    @BindView(R2.id.tv_cetificat)
    RTextView tvCetificat;
    @BindView(R2.id.iv_pic)
    AppCompatImageView ivPic;
    @BindView(R2.id.tv_content_title)
    TextView tvContentTitle;
    @BindView(R2.id.stv_name)
    SuperTextView stvName;
    @BindView(R2.id.stv_idnumber)
    SuperTextView stvIdnumber;
    @BindView(R2.id.stv_time)
    SuperTextView stvTime;
    @BindView(R2.id.ll_idcard_content)
    LinearLayout llIdcardContent;

    @AutoWired(name = Extras.CAR_ID)
    long carId;
    @AutoWired(name = Extras.CAR_NUMBER)
    String number;
    @AutoWired(name = Extras.CAR_IS_CETIFICAT)
    boolean carIsCetificat;
    @AutoWired(name = Extras.CAR_COLOR)
    String color;

    @Override
    protected void initArgs() {
        XRouter.getInstance().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.parksdk_fragment_car_certificate;
    }

    @Override
    protected void initViews() {
        tvContentTitle.setText("行驶证识别信息");
        stvName.setLeftString("车牌号");
        stvIdnumber.setLeftString("所有人");
        stvTime.setLeftString("注册日期");
        initCarInfo();
    }

    private void initCarInfo() {
        tvName.setText(number);
        rtvCarColorHelper = rtvCarColor.getHelper();
        rllCarColorHelper = rllCarColor.getHelper();
        if (!StringUtils.isEmpty(color)) {
            rtvCarColor.setText(Dictionary.Car.PlateColor.PlateColorNameMap.get(color));
            rtvCarColorHelper.setBackgroundColorNormal(ResUtils.getColor(Dictionary.Car.PlateColor.PalteColorMap.get(color)));
            rtvCarColorHelper.setTextColorNormal(ResUtils.getColor(Dictionary.Car.PlateColor.White.equals(color) ? R.color.color_3 : R.color.color_white));
            rtvCarColorHelper.setBorderWidthNormal(DensityUtils.dp2px(Dictionary.Car.PlateColor.White.equals(color)?1:0));
            rllCarColorHelper.setBorderColorNormal(ResUtils.getColor(Dictionary.Car.PlateColor.White.equals(color) ?R.color.color_3:Dictionary.Car.PlateColor.PalteColorMap.get(color)));
        }
        tvCetificat.setVisibility(carIsCetificat ? View.VISIBLE : View.GONE);
    }

    @SingleClick
    @OnClick({R2.id.btn_submit, R2.id.rtv_exchange_car, R2.id.iv_pic})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.rtv_exchange_car) {
            exchangeCar();
        } else if (id == R.id.iv_pic) {
            selectePicture(Extras.REQUEST_PICTURE_FRONT);
        } else if (id == R.id.btn_submit) {
            if (checkData()) checkCarCanVerify();
        }
    }

    private void exchangeCar() {
        openNewPageForResult(FragmentParkingPay.class, Extras.BASE_IS_SELECTED, Extras.BASE_SELECTED_CERTICICATE, Extras.REQUEST_CAR_SELECTE_CAR);
    }

    private boolean checkData() {
        if (StringUtils.isEmpty(stvName.getCenterEditValue())
                || StringUtils.isEmpty(stvTime.getCenterString())
                || StringUtils.isEmpty(stvIdnumber.getCenterString())) {
            XToastUtils.warning("识别信息有误,请重新上传行驶证照片");
            return false;
        }
        if (!number.equals(stvName.getCenterEditValue())) {
            XToastUtils.warning("识别信息有误,请重新上传行驶证照片");
            return false;
        }
        return true;
    }

    @Permission(STORAGE)
    private void selectePicture(int code) {
        Utils.getPictureSelector(this)
                .forResult(code);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case Extras.REQUEST_PICTURE_FRONT:
                    // 正面
                    handlerPic(data);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Intent data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) return;
        if (data == null) return;
        if (requestCode == Extras.REQUEST_CAR_SELECTE_CAR) updateDefaultCarFormExchange(data);
    }

    private void updateDefaultCarFormExchange(Intent data) {
        String json = data.getStringExtra(Extras.BASE_JSON);
        if (StringUtils.isEmpty(json)) return;
        Data_Car car = JsonUtil.fromJson(json, Data_Car.class);
        if (car == null) return;
        carId = car.getId();
        number = car.getCarNo();
        carIsCetificat = car.isVerified();
        color = car.getPlateColor();
        initCarInfo();
    }

    private void handlerPic(Intent data) {
        String path = getPicPath(data);
        if (StringUtils.isEmpty(path)) return;
        disPalyPic(ivPic, path);
        llIdcardContent.setVisibility(View.VISIBLE);
        queryOCRdata(path);
    }

    private String getPicPath(Intent data) {
        List<LocalMedia> list = PictureSelector.obtainMultipleResult(data);
        if (list == null || list.size() == 0) {
            XToastUtils.error("选择图片出现错误");
            return "";
        }
        LocalMedia media = list.get(0);
        if (media == null) return "";
        Log.e("camera",JsonUtil.toJson(media));
        int mimeType = media.getMimeType();
        if (mimeType == PictureMimeType.ofAudio()) {
            XToastUtils.warning("只能选择图片");
            return "";
        }
        String path;
        if (media.isCut() && !media.isCompressed()) {
            // 裁剪过
            path = media.getCutPath();
        } else if (media.isCompressed() || (media.isCut() && media.isCompressed())) {
            // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
            path = media.getCompressPath();
        } else {
            // 原图
            path = media.getPath();
        }
        return path;
    }

    private void disPalyPic(AppCompatImageView iv, String paht) {
        RequestOptions options = new RequestOptions()
                .centerCrop()
                .placeholder(R.color.color_f4)
                .diskCacheStrategy(DiskCacheStrategy.NONE);
        Glide.with(getContext())
                .load(paht)
                .apply(options)
                .into(iv);
    }

    @SuppressLint("CheckResult")
    private void queryOCRdata(String path) {
        File file = new File(path);
        if (!file.exists()) {
            XToastUtils.error("识别失败,未找到文件");
            return;
        }
        CustomRequest request = XHttp.custom();
        request.apiCall(ApiHelper.getInstance(request)
                .ocrvehiclelicense(file))
                .subscribeWith(new TipRequestSubscriber<Data_CarLicense>() {
                    @Override
                    protected void onSuccess(Data_CarLicense data) {
                        setOCRdata(data);
                    }

                    @Override
                    public void onError(ApiException e) {
                        XToastUtils.error(StringUtils.isEmpty(e.getMessage()) ? "识别出错,请重新尝试" : e.getMessage());
                    }
                });
    }

    private Data_CarLicense carLicense;

    private void setOCRdata(Data_CarLicense data) {
        carLicense = data;
        stvName.setCenterEditString(data.getCarNo());
        stvIdnumber.setCenterString(data.getOwner());
        stvTime.setCenterString(data.getRegisterDate());
    }

    private void checkCarCanVerify() {
        new MGetRequest(MyNetApi.CAR_CANVERIFY + carId + "/canVerify")
                .user()
                .execute(new TipRequestCallBack<Boolean>() {
                    @Override
                    public void onSuccess(Boolean data) throws Throwable {
                        if (data != null && data) showConfirmDialog();
                        else XToastUtils.warning("该车辆不支持认证");
                    }
                });
    }

    private void showConfirmDialog() {
        StringBuffer sb = new StringBuffer();
        sb.append("车牌号：")
                .append(stvName.getCenterEditValue())
                .append("\n")
                .append("所有人：")
                .append(stvIdnumber.getCenterString())
                .append("\n")
                .append("注册日期：")
                .append(stvTime.getCenterString());
        new SweetAlertDialog(getContext(), SweetAlertDialog.CONFIRM_TYPE)
                .setTitleText("请确认以下信息")
                .setConfirmContent("确认无误后请点击确认提交，如有错误请点击取消并重新拍摄上传")
                .setConfirmTitle(sb.toString())
                .setCancelClickListener(null)
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDilaog) {
                        sDilaog.dismiss();
                        submitConfirmData();
                    }
                }).show();
    }

    @SuppressLint("CheckResult")
    private void submitConfirmData() {
        CustomRequest request = XHttp.custom();
        request.call(ApiHelper.getInstance(request)
                .carVerify(carId, stvName.getCenterEditValue(), stvIdnumber.getCenterString(), stvTime.getCenterString()))
                .subscribeWith(new TipRequestSubscriber<CommonResult>() {
                    @Override
                    protected void onSuccess(CommonResult result) {
                        if (result.getCode() == 200) showSuccessDialog();
                        else showFailedDialog();
                    }

                    @Override
                    public void onError(ApiException e) {
                        showFailedDialog();
                    }
                });
    }

    private void showFailedDialog() {
        new SweetAlertDialog(getContext(), SweetAlertDialog.ERROR_TYPE)
                .setContentMinHeight(DensityUtils.dp2px(200))
                .setContentText("认证失败,请再试一次")
                .showCancelButton(false)
                .setConfirmText("好的")
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        sDialog.dismiss();
                    }
                }).show();
    }

    private void showSuccessDialog() {
        new SweetAlertDialog(getContext(), SweetAlertDialog.SUCCESS_TYPE)
                .setContentMinHeight(DensityUtils.dp2px(200))
                .setContentText("认证成功")
                .showCancelButton(false)
                .setConfirmText("返回")
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        XToastUtils.success("车辆认证成功");
                        Intent intent = new Intent();
                        intent.putExtra(Extras.BASE_SUCCESS_TYPE, true);
                        setFragmentResult(Activity.RESULT_OK, intent);
                        sDialog.dismiss();
                        popToBack();
                    }
                }).show();
    }

}
